<template>
  <div class="container">
    <h1 style="font-size: 22px">现有普通管理员列表</h1>
    <div>
      <a-row>
        <a-col :span="17">
        </a-col>
        <a-col :span="4">
          <a-button type="primary" @click="showModal" style="margin-bottom: 15px; font-size: 18px">
            <a-icon type="plus" style="font-size: 18px"/>添加管理员
          </a-button>
        </a-col>
        <a-col :span="3">
          <a-button type="primary" @click="tableToExcel" style="margin-bottom: 15px; font-size: 18px">
            导出excel表
          </a-button>
        </a-col>
      </a-row>
      <a-modal
        title="添加管理员"
        :visible="visible"
        :confirm-loading="confirmLoading"
        @ok="handleOk"
        @cancel="handleCancel"
      >
<!--        ref,prop用于表单校验;ref用于form,prop用于item;ref也可直接用于item-->
        <a-form-model :model="form" :label-col="labelCol" :wrapper-col="wrapperCol" ref="ruleForm" :rules="rules">
<!--          prop的值为表单域model字段-->
          <a-form-model-item label="姓名" prop="adminName">
            <a-input v-model="form.adminName"/>
          </a-form-model-item>
          <a-form-model-item label="密码" prop="adminPass">
            <a-input v-model="form.adminPass" />
          </a-form-model-item>
          <a-form-model-item label="电话" prop="adminPhone">
            <a-input v-model="form.adminPhone"/>
          </a-form-model-item>
          <a-form-model-item label="邮箱" prop="adminEmail">
            <a-input v-model="form.adminEmail"/>
          </a-form-model-item>

          <a-form-model-item label="性别" prop="adminSex">
            <a-radio-group v-model="form.adminSex" :default-value="1">
              <a-radio value = "1">
                男
              </a-radio>
              <a-radio value = "2">
                女
              </a-radio>
            </a-radio-group>
          </a-form-model-item>
        </a-form-model>
      </a-modal>
    </div>
    <a-table :data-source="data" :columns="columns" :rowKey="record => record.adminId"
    @change="onChange">
      <div
        slot="filterDropdown"
        slot-scope="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }"
        style="padding: 8px"
      >
        <a-input
          v-ant-ref="c => (searchInput = c)"
          :placeholder="`Search ${column.dataIndex}`"
          :value="selectedKeys[0]"
          style="width: 188px; margin-bottom: 8px; display: block;"
          @change="e => setSelectedKeys(e.target.value ? [e.target.value] : [])"
          @pressEnter="() => handleSearch(selectedKeys, confirm, column.dataIndex)"
        />
        <a-button
          type="primary"
          icon="search"
          size="small"
          style="width: 90px; margin-right: 8px"
          @click="() => handleSearch(selectedKeys, confirm, column.dataIndex)"
        >
          Search
        </a-button>
        <a-button size="small" style="width: 90px" @click="() => handleReset(clearFilters)">
          Reset
        </a-button>
      </div>
      <a-icon
        slot="filterIcon"
        slot-scope="filtered"
        type="search"
        :style="{ color: filtered ? '#108ee9' : undefined }"
      />

      <template slot="customRender" slot-scope="text, record, index, column">
        <span v-if="searchText && searchedColumn === column.dataIndex">
          <template
            v-for="(fragment, i) in text
              .toString()
              .split(new RegExp(`(?<=${searchText})|(?=${searchText})`, 'i'))"
          >
            <mark
              v-if="fragment.toLowerCase() === searchText.toLowerCase()"
              :key="i"
              class="highlight"
            >{{ fragment }}</mark
            >
            <template v-else>{{ fragment }}</template>
          </template>
        </span>
        <template v-else>
          {{ text }}
        </template>
      </template>

      <template slot="operation" slot-scope="text, record">
        <a-popconfirm v-if="data.length" title="确定删除?" @confirm="() => onDelete(record.adminId)">
          <!-- <a href="javascript:;">Delete</a> -->
          <a-icon type="delete" style="font-size: 22px"/>删除
        </a-popconfirm>
      </template>

    </a-table>
  </div>
</template>

<script>
export default {
  data () {
    return {
      data: [],
      searchText: '',
      searchInput: null,
      searchedColumn: '',
      columns: [
        {
          title: '生成的账号名',
          dataIndex: 'adminId',
          key: 'adminId'
        },
        {
          title: '密码',
          dataIndex: 'adminPass',
          key: 'adminPass'
        },
        {
          title: '用户名',
          dataIndex: 'adminName',
          key: 'adminName',
          scopedSlots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'customRender'
          },
          onFilter: (value, record) =>
            record.adminName
              .toString()
              .includes(value),
          // 自动添加输入焦点
          onFilterDropdownVisibleChange: visible => {
            if (visible) {
              setTimeout(() => {
                this.searchInput.focus()
              })
            }
          }
        },
        {
          title: '性别',
          dataIndex: 'adminSex',
          key: 'adminSex',
          customRender: function (text) {
            if (text === 1) {
              return '男'
            } else if (text === 2) {
              return '女'
            } else {
              return text
            }
          },
          filters: [
            {
              text: '男',
              value: 1
            },
            {
              text: '女',
              value: 2
            }
          ],
          onFilter: (value, record) => record.adminSex === value
        },
        {
          title: '电话',
          dataIndex: 'adminPhone',
          key: 'adminPhone'
        },
        {
          title: '邮箱地址',
          dataIndex: 'adminEmail',
          key: 'adminEmail'
        },
        {
          title: '操作',
          dataIndex: 'operation',
          scopedSlots: {
            customRender: 'operation'
          }
        }
      ],
      visible: false,
      confirmLoading: false,

      labelCol: { span: 6 },
      wrapperCol: { span: 14 },
      form: {
        adminName: '',
        adminPass: '',
        adminSex: '1',
        adminPhone: '',
        adminEmail: ''
      },
      rules: {
        adminName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        adminPass: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        adminPhone: [{ required: true, message: '请输入电话', trigger: 'blur' }]
      }
    }
  },
  created () {
    this.$http.get('/admins')
      .then((resp) => {
        if (resp.body.status === 401) {
          this.$message.error('请先登录')
          this.$router.push('/login')
        } else {
          if (JSON.parse(localStorage.userInfo)) {
            if (JSON.parse(localStorage.userInfo).adminRole === 1) {
              this.$message.error('对不起,你没有超级管理员的权限')
              this.$router.push('/home/users')
            } else {
              this.data = resp.body.data
            }
          }
        }
      }, (error) => {
        console.log(error)
        this.$message.error('网络故障')
      })
  },
  methods: {
    handleSearch (selectedKeys, confirm, dataIndex) {
      confirm()
      this.searchText = selectedKeys[0]
      this.searchedColumn = dataIndex
    },

    handleReset (clearFilters) {
      clearFilters()
      this.searchText = ''
    },

    onDelete (key) {
      this.$http.delete('/admin/' + key)
        .then((resp) => {
          if (resp.body.status === 200) {
            const data = [...this.data]
            this.data = data.filter(item => item.adminId !== key)
            this.$message.success('删除成功')
          } else {
            this.$message.error('删除异常')
          }
        }, (error) => {
          console.log(error)
          if (error.status === 401) {
            this.$message.error('请先登录')
            this.$router.push('/login')
          } else {
            this.$message.error('未知错误')
          }
        })
    },

    onChange (pagination, filters, sorter) {
    },

    showModal () {
      this.visible = true
    },
    handleOk () {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          this.confirmLoading = true
          this.$http.post('/admin',
            { adminName: this.form.adminName, adminPass: this.form.adminPass, adminSex: this.form.adminSex, adminPhone: this.form.adminPhone, adminEmail: this.form.adminEmail }, { emulateJSON: true })
            .then((resp) => {
              if (resp.body.status === 200) {
                this.$message.success('添加成功')
                this.form.adminName = ''
                this.form.adminPass = ''
                this.form.adminSex = '1'
                this.form.adminPhone = ''
                this.form.adminEmail = ''
                this.confirmLoading = false
                this.visible = false
                this.$http.get('/admins')
                  .then((resp) => {
                    this.data = resp.body.data
                  }, (error) => {
                    console.log(error)
                  })
              } else {
                this.$message.error('添加异常')
              }
            }, (error) => {
              console.log(error)
              if (error.status === 401) {
                this.$message.error('请先登录')
                this.$router.push('/login')
              } else {
                this.$message.error('未知错误')
              }
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleCancel () {
      this.visible = false
    },
    tableToExcel () {
      let str = '<tr><td>生成的账户名</td><td>姓名</td><td>密码</td><td>性别</td><td>电话</td><td>邮箱地址</td></tr>'
      // 循环遍历，每行加入tr标签，每个单元格加td标签
      for (let i = 0; i < this.data.length; i++) {
        str += '<tr>'
        for (const item in this.data[i]) {
          // 增加\t为了不让表格显示科学计数法或者其他格式
          if (item === 'adminSex') {
            if (this.data[i][item] === 1) {
              str += '<td>男</td>'
            } else if (this.data[i][item] === 2) {
              str += '<td>女</td>'
            } else {
              str += '<td>未知</td>'
            }
          } else if (item === 'adminRole') {
          } else {
            str += `<td>${this.data[i][item] + '\t'}</td>`
          }
        }
        str += '</tr>'
      }
      // Worksheet名
      const worksheet = '普通管理员信息表'
      const uri = 'data:application/vnd.ms-excel;base64,'

      // 下载的表格模板数据
      const template = `<html xmlns:o="urn:schemas-microsoft-com:office:office"
      xmlns:x="urn:schemas-microsoft-com:office:excel"
      xmlns="http://www.w3.org/TR/REC-html40" lang="en">
      <head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>
        <x:Name>${worksheet}</x:Name>
        <x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>
        </x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]-->
        <title>普通管理员信息表</title></head><body><table>${str}</table></body></html>`
      // 下载模板
      const link = document.createElement('a')
      link.href = uri + this.base64(template)
      // 对下载的文件命名
      link.download = '普通管理员信息表.xls'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    },
    base64 (s) {
      return window.btoa(unescape(encodeURIComponent(s)))
    }
  }
}
</script>
<style scoped>
  .highlight {
    background-color: rgb(255, 192, 105);
    padding: 0;
  }
  .container{
  }
</style>
